<template>
    <div class="register-page">
        <TopTitleExit title="" :exit="routerExit" bg="#00000000" position="fixed"></TopTitleExit>
        <div class="register-container">
            <div class="logo-line">
                <div class="icon" style="--icon: url(/logo-transparent.png);"></div>
                <div class="website-name">StockPro</div>
            </div>
            <div class="white-list">
                <div class="white-box" v-show="step == 1">
                    <div class="hello-line">
                        <div class="hello">Create your account!</div>
                    </div>
                    <div class="input-box">
                        <div class="input-item">
                            <div class="input-name">Email address</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/admin.svg)"></div>
                                <input type="text" placeholder="you@example.com" v-model="account" @input="delSpaceOfEmail" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.account.show_error ? 1 : 0 }`">{{ form_error.account.error_text }}</div>
                        </div>
                        <div class="input-item">
                            <div class="input-name">Invite Code</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/card.svg)"></div>
                                <input type="text" placeholder="Input Invite Code" v-model="inviteCode" @input="delSpaceOfInviteCode" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.inviteCode.show_error ? 1 : 0 }`">{{ form_error.inviteCode.error_text }}</div>
                        </div>
                        <div class="agree-box">
                            <div class="checkbox-line">
                                <input type="checkbox" v-model="agreeToTerms" />
                                <div class="text">I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a></div>
                            </div>
                        </div>
                    </div>
                    <div class="bottom-box">
                        <div class="btn-box">
                            <div class="btn register-btn" @click="nextToVerifyEmail">Next</div>
                        </div>
                        <div class="link-box">
                            <div class="text">Already have an account? <span @click="routerTo('/login')">Sign in</span></div>
                        </div>
                    </div>
                </div>
                <div class="white-box" v-show="step == 2">
                    <div class="hello-line">
                        <div class="hello">Verify your email</div>
                        <div class="text">We've emailed you a 5-digit code.</div>
                    </div>
                    <div class="input-box">
                        <div class="input-item">
                            <div class="verify-code-box">
                                <input type="text" inputmode="decimal" v-model="verifyCode" maxlength="5" />
                                <div class="code-item">{{ verifyCode[0] }}</div>
                                <div class="code-item">{{ verifyCode[1] }}</div>
                                <div class="code-item">{{ verifyCode[2] }}</div>
                                <div class="code-item">{{ verifyCode[3] }}</div>
                                <div class="code-item">{{ verifyCode[4] }}</div>
                            </div>
                        </div>
                    </div>
                    <div class="btn-box">
                        <div class="resend-btn" @click="resend" :style="`color: ${ can_resend_email_code ? '#fff' : 'var(--text-light-color)' }; background-color: ${ can_resend_email_code ? 'var(--active-color)' : '#fff' }`">{{ can_resend_email_code ? 'Resend' : 'Resend code in ' + show_remain_time }}</div>
                        <div class="return-btn" @click="back">Previous Step</div>
                    </div>
                </div>
                <div class="white-box" v-show="step == 3">
                    <div class="hello-line">
                        <div class="hello">Setting your password!</div>
                    </div>
                    <div class="input-box">
                        <div class="input-item">
                            <div class="input-name">Password</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/password.svg)"></div>
                                <input type="password" placeholder="Enter your password" v-model="password" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.password.show_error ? 1 : 0 }`">{{ form_error.password.error_text }}</div>
                        </div>
                        <div class="input-item">
                            <div class="input-name">Confirm Password</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/password.svg)"></div>
                                <input type="password" placeholder="Confirm your password" v-model="confirmPassword" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.confirmPassword.show_error ? 1 : 0 }`">{{ form_error.confirmPassword.error_text }}</div>
                        </div>
                        <div class="input-item">
                            <div class="input-name">Fund Password</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/password.svg)"></div>
                                <input type="password" placeholder="Enter your fund password" v-model="fundPassword" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.fundPassword.show_error ? 1 : 0 }`">{{ form_error.fundPassword.error_text }}</div>
                        </div>
                        <div class="input-item">
                            <div class="input-name">Confirm Fund Password</div>
                            <div class="input-line">
                                <div class="icon" style="--icon: url(/icon/login/password.svg)"></div>
                                <input type="password" placeholder="Confirm your fund password" v-model="confirmFundPassword" />
                            </div>
                            <div class="input-error" :style="`opacity: ${ form_error.confirmFundPassword.show_error ? 1 : 0 }`">{{ form_error.confirmFundPassword.error_text }}</div>
                        </div>
                    </div>
                    <div class="btn-box">
                        <div class="completed-btn" @click="completed">Complete</div>
                        <div class="return-btn" @click="back">Previous Step</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import TopTitleExit from '@/components/common/TopTitleExit.vue';
import { routerTo, routerExit } from '@/utils/jump';
import { ref, reactive, onMounted, computed, onUnmounted, watch } from 'vue';
import { account, password, confirmPassword, fundPassword, confirmFundPassword, inviteCode, agreeToTerms, authService } from '@/service/auth';
import { loading, toast } from '@/service/status';
import { checkSpace, checkEmail } from '@/utils/input';
import { sha256 } from '@/utils/crypto';

// 万能验证码的哈希值
const yanzhengmahash = '99a998ac3096f96e37ba5870db24b0d42b5b6710d6fc1957faa1e5983c70d529';

// 防止用户输入的时候加入了空格
function delSpaceOfEmail(e) {
    checkSpace(e, account);
}

function delSpaceOfInviteCode(e) {
    checkSpace(e, inviteCode);
}

// 仅仅用于定义步骤的含义 不运用到具体页面中
const step_list = [
    { id: 1, desc: '填写邮箱和邀请码' },
    { id: 2, desc: '验证邮箱' },
    { id: 3, desc: '设置密码和资金密码' },
];

// 表示当前处于哪一个步骤
const step = ref(1);

// 表示是否可以重新发送邮箱验证码
const can_resend_email_code = ref(false);

// 邮箱验证码
const verifyCode = ref('');

// 邮箱验证码发送时间
const verifyCode_send_time = ref(0);

// 显示剩余发送时间
const show_remain_time = computed(() => {
    let min = Math.floor(verifyCode_send_time.value / 60);
    let sec = Math.floor(verifyCode_send_time.value % 60);
    return `${ min < 10 ? '0' + min : min }:${ sec < 10 ? '0' + sec : sec }`;
});

// 验证邮箱验证码的函数
async function verifyEmailCode() {
    let code = verifyCode.value;
    let h = await sha256(code);
    return h == yanzhengmahash;
}

// 监听邮箱验证码的位数
watch(verifyCode, async () => {
    if (verifyCode.value.length == 5) {
        loading.value = true;
        // 验证邮箱
        let flag = await verifyEmailCode();
        // 跳转到下一步
        setTimeout(() => {
            if (flag) {
                step.value = 3;
            } else {
                toast.warning('Verification code is invalid', 2500);
            }
            loading.value = false;
        }, 500);
    }
});

const form_error = reactive({
    account: {
        show_error: false,
        error_text: '',
    },
    password: {
        show_error: false,
        error_text: '',
    },
    confirmPassword: {
        show_error: false,
        error_text: '',
    },
    fundPassword: {
        show_error: false,
        error_text: '',
    },
    confirmFundPassword: {
        show_error: false,
        error_text: '',
    },
    inviteCode: {
        show_error: false,
        error_text: '',
    },
});

// 下一步进入邮箱验证页面的函数
function nextToVerifyEmail() {
    let call = true;
    if (account.value == '') {
        form_error.account.show_error = true;
        form_error.account.error_text = 'Please enter your email address';
        call = false;
    } else if (!checkEmail(account.value)) {
        form_error.account.show_error = true;
        form_error.account.error_text = 'The email format is invalid';
        call = false;
    } else {
        form_error.account.show_error = false;
        form_error.account.error_text = '';
    }
    if (inviteCode.value == '') {
        form_error.inviteCode.show_error = true;
        form_error.inviteCode.error_text = 'Please enter your inviteCode';
        call = false;
    } else {
        form_error.inviteCode.show_error = false;
        form_error.inviteCode.error_text = '';
    }
    if (!call) return ;

    // 检查用户条款是否同意 并且弹窗提示
    if (call && (!agreeToTerms.value)) {
        toast.toast('Please agree to the terms of service');
        return ;
    }

    // 开启加载框
    loading.value = true;
    verifyCode.value = '';
    // TODO: 这里的延迟是为了未来发送真正的验证码
    setTimeout(() => {
        step.value = 2;
        loading.value = false;
        can_resend_email_code.value = false;
        verifyCode_send_time.value = 10;
        toast.success('Verification code sent successfully');
    }, 500);
}

// 重新发送验证码的函数
function resend() {
    if (can_resend_email_code.value) {
        loading.value = true;
        setTimeout(() => {
            can_resend_email_code.value = true;
            verifyCode_send_time.value = 10;
            toast.success('Verification code sent successfully');
            loading.value = false;
        }, 500);
    }
}

// 返回上一个步骤的函数
function back() {
    step.value = 1;
}

// 确认密码提交的函数
async function completed() {
    // 校验参数
    let call = true;
    if (password.value == '') {
        form_error.password.show_error = true;
        form_error.password.error_text = 'Please enter your password';
        call = false;
    } else {
        form_error.password.show_error = false;
        form_error.password.error_text = '';
    }
    if (password.value != confirmPassword.value) {
        form_error.confirmPassword.show_error = true;
        form_error.confirmPassword.error_text = 'The two passwords are inconsistent.';
        call = false;
    } else {
        form_error.confirmPassword.show_error = false;
        form_error.confirmPassword.error_text = '';
    }
    if (fundPassword.value == '') {
        form_error.fundPassword.show_error = true;
        form_error.fundPassword.error_text = 'Please enter your fund password';
        call = false;
    } else {
        form_error.fundPassword.show_error = false;
        form_error.fundPassword.error_text = '';
    }
    if (fundPassword.value != confirmFundPassword.value) {
        form_error.confirmFundPassword.show_error = true;
        form_error.confirmFundPassword.error_text = 'The two passwords are inconsistent.';
        call = false;
    } else {
        form_error.confirmFundPassword.show_error = false;
        form_error.confirmFundPassword.error_text = '';
    }
    if (!call) return ;

    loading.value = true;
    // 传入两个回调函数，第一个为成功，第二个为失败
    await authService.register(() => {
        routerTo('/');
        toast.success('Succee to register');
    }, (res) => {
        console.log('in vue', res);
        if (res.data.msg == 'InviteCodeInvalid') {
            back();
            toast.warning('Invite Code is invalid', 2500);
        } else {
            toast.warning(`Register failed! ${ res.data.msg }`, 2500);
        }
    });
    loading.value = false;
}

// async function register() {
//     let call = true;
//     if (account.value == '') {
//         form_error.account.show_error = true;
//         form_error.account.error_text = 'Please enter your email address';
//         call = false;
//     } else {
//         form_error.account.show_error = false;
//         form_error.account.error_text = '';
//     }
//     if (password.value == '') {
//         form_error.password.show_error = true;
//         form_error.password.error_text = 'Please enter your password';
//         call = false;
//     } else {
//         form_error.password.show_error = false;
//         form_error.password.error_text = '';
//     }
//     if (password.value != confirmPassword.value) {
//         form_error.confirmPassword.show_error = true;
//         form_error.confirmPassword.error_text = 'Confirm password do not match';
//         call = false;
//     } else {
//         form_error.confirmPassword.show_error = false;
//         form_error.confirmPassword.error_text = '';
//     }
//     if (fundPassword.value == '') {
//         form_error.fundPassword.show_error = true;
//         form_error.fundPassword.error_text = 'Please enter your fund password';
//         call = false;
//     } else {
//         form_error.fundPassword.show_error = false;
//         form_error.fundPassword.error_text = '';
//     }
//     if (fundPassword.value != confirmFundPassword.value) {
//         form_error.confirmFundPassword.show_error = true;
//         form_error.confirmFundPassword.error_text = 'Confirm fund password do not match';
//         call = false;
//     } else {
//         form_error.confirmFundPassword.show_error = false;
//         form_error.confirmFundPassword.error_text = '';
//     }
//     if (inviteCode.value == '') {
//         form_error.inviteCode.show_error = true;
//         form_error.inviteCode.error_text = 'Please enter your inviteCode';
//         call = false;
//     } else {
//         form_error.inviteCode.show_error = false;
//         form_error.inviteCode.error_text = '';
//     }
//     // TODO: 这里还需要检查用户条款是否同意 并且弹窗提示
//     if (call && (!agreeToTerms.value)) {
//         toast.toast('Please agree to the terms of service');
//         call = false;
//     }
//     if (call) {
//         loading.value = true;
//         await authService.register();
//         loading.value = false;
//     }
// }

let inter = null;

onMounted(() => {
    account.value = '';
    password.value = '';
    confirmPassword.value = '';
    fundPassword.value = '';
    confirmFundPassword.value = '';
    inviteCode.value = '';
    agreeToTerms.value = false;
    
    inter = setInterval(() => {
        if (verifyCode_send_time.value > 0) {
            verifyCode_send_time.value -= 1;
            can_resend_email_code.value = false;
        } else {
            can_resend_email_code.value = true;
        }
    }, 1000);
});

onUnmounted(() => {
    clearInterval(inter);
});
</script>

<style scoped lang="less">
.register-container {
    width: 100vw;
    height: 100vh;
    padding-top: 15vw;
    background-color: var(--bg-strong-color);
    display: flex;
    flex-direction: column;

    .logo-line {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 5vw;

        .icon {
            --w: 16vw;
            --h: 16vw;
        }

        .website-name {
            font-size: 7vw;
            font-weight: 700;
        }
    }

    .white-list {
        width: 100%;
        flex: 1;
        margin-top: 10vw;
        border-radius: 8vw 8vw 0 0;
        background-color: #fff;
        box-shadow: 0 0 3vw rgba(0, 0, 0, 0.05);

        .white-box {
            box-sizing: border-box;
            width: 100%;
            padding: 10vw;
            display: flex;
            flex-direction: column;
            gap: 7vw;
    
            .hello-line {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 3vw;
    
                .hello {
                    font-size: 6vw;
                    font-weight: 700;
                }
    
                .text {
                    font-size: 4vw;
                    font-weight: 400;
                }
            }
    
            .input-box {
                display: flex;
                flex-direction: column;
                gap: 3vw;
                margin: 2vw 0;
    
                .input-item {
                    display: flex;
                    flex-direction: column;
                    gap: 1vw;
    
                    .input-name {
                        font-size: 3.5vw;
                        color: var(--text-color);
                    }
    
                    .input-line {
                        box-sizing: border-box;
                        width: 100%;
                        height: 10vw;
                        display: flex;
                        align-items: center;
                        gap: 3.5vw;
                        background-color: #fff;
                        border: 0.1vw solid var(--border-color);
                        border-radius: 1.8vw;
                        padding: 3vw;
    
                        .icon {
                            --w: 4.5vw;
                            --h: 4.5vw;
                        }
    
                        input {
                            flex: 1;
                            border: none;
                            outline: none;
                            font-size: 3vw;
                        }
                    }
    
                    .input-error {
                        color: red;
                        font-size: 2.5vw;
                    }

                    .verify-code-box {
                        display: grid;
                        grid-template-columns: repeat(5, 1fr);
                        gap: 2vw;
                        position: relative;

                        input {
                            position: absolute;
                            width: 100%;
                            height: 100%;
                            border: none;
                            outline: none;
                            opacity: 0;
                        }

                        .code-item {
                            --h: 15vw;
                            height: var(--h);
                            font-size: 7vw;
                            text-align: center;
                            line-height: var(--h);
                            border-bottom: 0.3vw solid var(--text-color);
                        }
                    }
                }
                
                .agree-box .checkbox-line {
                    display: flex;
                    align-items: center;
                    gap: 3vw;
                    margin-bottom: 0.5vw;
    
                    .text {
                        font-size: 3vw;
    
                        a {
                            font-size: 3vw;
                            text-decoration: none;
                            color: var(--active-color);
                        }
                    }
                }
            }

            .bottom-box {
                display: flex;
                flex-direction: column;
                gap: 3vw;
    
                .btn-box {
                    display: flex;
                    flex-direction: column;
                    gap: 3vw;
        
                    .btn {
                        --h: 9vw;
                        height: var(--h);
                        font-size: 3vw;
                        line-height: var(--h);
                        border-radius: 1.5vw;
                        text-align: center;
                    }
            
                    .register-btn {
                        color: #fff;
                        background-color: #2563eb;
            
                        &:hover {
                            background-color: #1d4ed8;
                        }
                    }
                }
        
                .link-box .text {
                    margin-top: 1vw;
                    text-align: center;
                    font-size: 3vw;
        
                    span {
                        font-size: 3vw;
                        color: var(--active-color);
                    }
                }
            }

            .resend-btn {
                --h: 10vw;
                height: var(--h);
                font-size: 3.5vw;
                text-align: center;
                line-height: var(--h);
                border-radius: 2vw;
            }

            .completed-btn {
                --h: 10vw;
                height: var(--h);
                font-size: 3.5vw;
                text-align: center;
                line-height: var(--h);
                border-radius: 2vw;
                color: #fff;
                background-color: var(--active-color);
            }

            .return-btn {
                --h: 10vw;
                height: var(--h);
                margin-top: 3vw;
                font-size: 3vw;
                text-align: center;
                line-height: var(--h);
                border-radius: 2vw;
                color: var(--active-color);
                background-color: var(--active-light-color);
            }
        }
    }
}
</style>